import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import {api} from '../constant'
import {getCookie} from '@/utils/cookie'
import {Message} from 'element-ui'

axios.defaults.timeout = 5000
axios.defaults.baseURL = api.BASE_API

axios.interceptors.request.use(config => {
    config.headers = {
        'Content-Type': 'application/json',
        'X-Accel-Redirect': '/api'
    }
    let token = getCookie('token')
    if (token) {
        config.headers.authorization = `Bearer ${token}`
    }
    return config
})
axios.interceptors.response.use(response => {
    if (response.data.code === 20007) {
        Vue.$router.push({
            path: '/login'
        })
    }
    return response
}, error => {
    switch (error.response.status) {
        case 401:
            Message.error('您需要登录才能进行此操作')
            break
        case 403:
            Message.error('您无权访问此接口')
            break
        case 500:
            Message.error('服务器内部错误，请重试')
            break
        case 504:
            Message.error('服务没有部署完成，请稍后重试')
    }
})

Vue.use(VueAxios, axios)
